package com.hongxun.design.adapters;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.activitys.RegeditActivity;
import com.hongxun.design.bean.CreateDistanceBean;
import com.hongxun.design.listeners.MClickListener;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.object_properties.MyMessage;
import com.hongxun.design.ui.dialogstyle.MyDialog;
import com.hongxun.design.ui.myiossheet.ActionSheet;
import com.hongxun.design.utils.PopwindowUtil;
import com.hongxun.design.utils.camerautil.CameraUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.imageutil.UriUtil;

import java.util.List;

/**
 * Created by zerdoor_pc on 2016/4/29.
 */
public class RegeditAdapter extends BaseAdapter {
    private List<CreateDistanceBean> beanList;
    LayoutInflater inflater;
    Activity context;
    boolean flag = true;
    TextView textView;
    private final int UPDATE = 3;

    public RegeditAdapter(List<CreateDistanceBean> beanList, Activity context) {
        this.beanList = beanList;
        this.context = context;
        inflater = LayoutInflater.from(context);
    }

    public List<CreateDistanceBean> getData() {
        return beanList;
    }

    public void setIcon(String path) {
        CreateDistanceBean bean= beanList.get(0);
        if (bean.getTitleCode().equals(MString.avatar)) {
            bean.setValue(path);
            notifyDataSetChanged();
        }else{
            ToastShow.showShort(context,"用户头像修改失败！");
        }
    }

    @Override
    public int getCount() {
        return beanList.size();
    }

    @Override
    public Object getItem(int i) {
        return beanList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    private int index = -1;

    @Override
    public int getItemViewType(int position) {
        return Integer.parseInt(beanList.get(position).getTypecode());
    }

    @Override
    public int getViewTypeCount() {
        return 4;
    }


    @Override
    public View getView(final int position, View convertView, ViewGroup viewGroup) {
        int ViewType = getItemViewType(position);
        Holder holder = null;
        SecretsetHolder secretsetHolder = null;
        InfoHolder infoHolder = null;
        if (convertView == null) {
            if (ViewType == 2) {
                convertView = inflater.inflate(R.layout.listview_item_secretset, null);
                secretsetHolder = new SecretsetHolder(convertView);
                convertView.setTag(secretsetHolder);
            } else if (ViewType == 3) {
                convertView = inflater.inflate(R.layout.listview_item_userinfoset, null);
                infoHolder = new InfoHolder(convertView);
                convertView.setTag(infoHolder);
            } else {
                convertView = inflater.inflate(R.layout.listview_item_regedit, null);
                holder = new Holder(convertView);
                convertView.setTag(holder);
            }


        } else {
            if (ViewType == 2) {
                secretsetHolder = (SecretsetHolder) convertView.getTag();
            } else if (ViewType == 3) {
                infoHolder = (InfoHolder) convertView.getTag();
            } else {
                holder = (Holder) convertView.getTag();
            }
        }

        CreateDistanceBean bean;
        try {
            bean = beanList.get(position);
            if (ViewType == 2) {
                secretsetHolder.secretset_name.setText(bean.getTitle() + ":");
                if (bean.getValue().length() == 0) {
                    if (bean.getTitleCode().equals(MString.security_problem1) || bean.getTitleCode().equals(MString.security_problem2)) {
                        secretsetHolder.secretset_write.setVisibility(View.VISIBLE);
                        secretsetHolder.secretset_text.setVisibility(View.GONE);
                    }

                } else {
                    if (bean.getTitleCode().equals(MString.security_problem1) || bean.getTitleCode().equals(MString.security_problem2)) {
                        secretsetHolder.secretset_write.setVisibility(View.GONE);
                        secretsetHolder.secretset_text.setVisibility(View.VISIBLE);
                    }
                }
                secretsetHolder.secretset_write.setText(bean.getValue());
                secretsetHolder.secretset_text.setText(bean.getValue());
                secretsetHolder.secretset_write.addTextChangedListener(new MTextWatcher(bean) {
                });
            } else if (ViewType == 3) {
                //infoHolder
                if (bean.getTitleCode().equals(MString.avatar)) {
                    //头像
                    infoHolder.icon.setVisibility(View.VISIBLE);
                    infoHolder.name.setVisibility(View.INVISIBLE);
                    infoHolder.icon.setImageURI(UriUtil.getUri(bean.getValue()));
                    infoHolder.value.setText(bean.getTitle());
                    MyLog.L(MString.SUCCESSED+" avatar= "+UriUtil.getUri(bean.getValue()));
                } else {
                    //正常条目
                    infoHolder.icon.setVisibility(View.GONE);
                    infoHolder.name.setVisibility(View.VISIBLE);
                    infoHolder.name.setText(bean.getTitle());
//                    if (bean.getTitleCode().equals(MString.birthday) && bean.getValue().length() > 0) {
//                        infoHolder.value.setText(TimeUtil.time(bean.getValue(), "yyyy-MM-dd"));
//                    } else
                    if (bean.getTitleCode().equals(MString.sex) && bean.getValue().length() > 0){
                                if (bean.getValue().equals(MString.grilCode)){
                                    infoHolder.value.setText(MString.gril);
                                }else{
                                    infoHolder.value.setText(MString.boy);
                                }
                    }else{
                        infoHolder.value.setText(bean.getValue());
                    }
                }

                infoHolder.item.setOnClickListener(new MClickListener(position, bean, infoHolder) {
                    @Override
                    public void onClick(View view, int position, Object msg) {
                        //弹出输入框
                        CreateDistanceBean bean = (CreateDistanceBean) msg;

                        if (bean.getTitleCode().equals(MString.avatar)) {
                            openSheet(context, "选择方式", "相册", "拍照");
                        } else if (bean.getTitleCode().equals(MString.sex)) {
                            openSheet(context, bean, "选择性别", MString.boy, MString.gril);
                        } else if (bean.getTitleCode().equals(MString.birthday)) {
                            PopwindowUtil.timeChoice(context, bean, view, handler, UPDATE);
                        } else {
                            MyDialog.dialogForInputInfo(context, msg, handler, UPDATE);
                        }
                    }
                });
            } else {
                //判断是否为输入框
                holder.regedit_name.setText(bean.getTitle());
                holder.regedit_write.setText(bean.getValue());

                if (ViewType == 0) {
                    holder.regedit_right.setVisibility(View.GONE);
                } else {
                    textView = holder.regedit_right;
                    holder.regedit_right.setVisibility(View.VISIBLE);
                    holder.regedit_right.setOnClickListener(new MClickListener(position, bean) {
                        @Override
                        public void onClick(View view, int position, Object msg) {
                            if (flag) {//按钮可点
                                if (beanList.get(position - 1).getValue().length() == 0) {
                                    ToastShow.showShort(context, "手机号不能为空！");
                                } else {
                                    checkButton((TextView) view, beanList.get(position - 1).getValue());
                                }
                            }
                        }
                    });
                    if (flag) {
                        uncheckButton(holder.regedit_right);
                    }
                }

                holder.regedit_write.addTextChangedListener(new MTextWatcher(bean) {
                });

                if (bean.getTitleCode().equals(MString.phone) && ((RegeditActivity) context).type.equals(MString.ModifyPassword)) {
                    holder.regedit_write.setEnabled(false);
                } else if (bean.getTitleCode().equals(MString.mobilePhone)) {
                    holder.regedit_write.setInputType(InputType.TYPE_CLASS_PHONE);
                } else if (bean.getTitleCode().equals(MString.pwd) || bean.getTitleCode().equals(MString.password)) {
                    holder.regedit_write.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                } else if (bean.getTitleCode().equals(MString.username)) {
                    holder.regedit_write.setInputType(InputType.TYPE_CLASS_TEXT);
                } else if (bean.getTitleCode().equals(MString.ident_code)) {
                    holder.regedit_write.setInputType(InputType.TYPE_CLASS_TEXT);
                }
            }


        } catch (Exception e) {
            MyLog.L(MyApp.AppName + "适配错误：" + e.toString());
        }

        return convertView;

    }

    class MTextWatcher implements TextWatcher {
        CreateDistanceBean bean;

        MTextWatcher(CreateDistanceBean bean) {
            this.bean = bean;
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (!bean.getValue().equals(editable.toString())) {
                bean.setValue(editable.toString());
            }
        }
    }


    class Holder {
        public TextView regedit_name, regedit_right;
        public EditText regedit_write;
        public RelativeLayout regedit_item_button;

        Holder(View convertView) {
            regedit_item_button = (RelativeLayout) convertView.findViewById(R.id.regedit_item_button);
            regedit_name = (TextView) convertView.findViewById(R.id.regedit_name);
            regedit_right = (TextView) convertView.findViewById(R.id.regedit_right);
            regedit_write = (EditText) convertView.findViewById(R.id.regedit_write);
        }
    }

    class SecretsetHolder {
        public TextView secretset_name, secretset_text;
        public EditText secretset_write;
        public RelativeLayout secretset_item_button;

        SecretsetHolder(View convertView) {
            secretset_item_button = (RelativeLayout) convertView.findViewById(R.id.secretset_item_button);
            secretset_name = (TextView) convertView.findViewById(R.id.secretset_name);
            secretset_write = (EditText) convertView.findViewById(R.id.secretset_write);
            secretset_text = (TextView) convertView.findViewById(R.id.secretset_text);
        }
    }

    class InfoHolder {
        TextView name, right, value;
        SimpleDraweeView icon;
        RelativeLayout item;

        InfoHolder(View view) {
            icon = (SimpleDraweeView) view.findViewById(R.id.userinfoset_icon);
            name = (TextView) view.findViewById(R.id.userinfoset_name);
            right = (TextView) view.findViewById(R.id.userinfoset_right);
            value = (TextView) view.findViewById(R.id.userinfoset_value);
            item = (RelativeLayout) view.findViewById(R.id.userinfoset_item);
            SetTypeface.set(right, IconSourse.RIGHTARROW);
        }
    }

    //头像
    private void openSheet(Activity activity, final String... titles) {
        activity.setTheme(R.style.ActionSheetStyleIOS7);
        ActionSheet menuView = new ActionSheet(activity);
        menuView.setCancelButtonTitle("取消");// before add items
        menuView.addItems(titles);

        menuView.setItemClickListener(new ActionSheet.MenuItemClickListener() {
            @Override
            public void onItemClick(int itemPosition) {

                if (itemPosition == 0) return;
                if (itemPosition == 1) {
                    CameraUtil.pickPhoto(RegeditActivity.Code_Select);//相册
                } else {
                    //CameraUtil.selectPicFromCamera(RegeditActivity.Code_Select,  Constant.TMP_PATH);
                    CameraUtil.openCamera(RegeditActivity.Code_Pick);//拍照
                }
            }
        });
        menuView.setCancelableOnTouchMenuOutside(true);
        menuView.showMenu();
    }

    /**
     * 性别*
     */
    private void openSheet(Activity activity, final Object msg, final String... titles) {
        final CreateDistanceBean bean = (CreateDistanceBean) msg;
        activity.setTheme(R.style.ActionSheetStyleIOS7);
        ActionSheet menuView = new ActionSheet(activity);
        menuView.setCancelButtonTitle("取消");// before add items
        menuView.addItems(titles);
        menuView.setItemClickListener(new ActionSheet.MenuItemClickListener() {
            @Override
            public void onItemClick(int itemPosition) {
                if (itemPosition == 0) return;
                if (itemPosition>=1){
                    bean.setValue(itemPosition-1+"");
                    notifyDataSetChanged();
                }
            }
        });
        menuView.setCancelableOnTouchMenuOutside(true);
        menuView.showMenu();
    }


    private Handler handler = new Handler() {
        int i = 0;
        String phone = "";

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HttpStringUtil.SUCCESSED:
                    String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                    if (s.equals(MString.TRUE)) {
                        ToastShow.showShort(context, "验证码发送成功！");
                        handler.sendEmptyMessage(1);
                    } else {
                        i = 0;
                        uncheckButton(textView);
                        ToastShow.showShort(context, s);
                        ToastShow.showShort(context, "验证码发送失败！");
                    }
                    break;
                case 1:
                    if (textView != null) {
                        textView.setText(" 已发送" + i + "秒 ");
                        i++;
                        if (i <= 60) {
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    handler.sendEmptyMessage(1);
                                }
                            }, 1000);
                        } else {
                            i = 0;
                            uncheckButton(textView);
                        }
                    }
                    break;
                case 2:
                    i = 0;
                    phone = (String) msg.obj;
                    String code = MString.RegisterKey;
                    int templet=0;
                    switch (((RegeditActivity) context).type) {
                        case MString.REGEDIT:
                            code = MString.RegisterKey;
                            templet=0;
                            break;
                        case MString.SMS:
                            code = MString.FindPasswordKey;
                            templet=1;
                            break;
                        case MString.SECRET:
                            code = MString.FindPasswordKey;
                            templet=1;
                            break;

                        case MString.ModifyPassword:
                            code = MString.ModifyPasswordKey;
                            templet=1;
                            break;
                    }
                    MyApp.HTTP.SendIdentCode(handler, HttpStringUtil.SUCCESSED, phone, code,templet);
                    break;
                case HttpStringUtil.ERROR:
                    i = 0;
                    uncheckButton(textView);
                    ToastShow.showShort(context, "验证码发送失败！");
                    break;


                case UPDATE:
                    notifyDataSetChanged();
                    break;

            }


        }
    };

    private void checkButton(final TextView view, String phone) {
        flag = false;
        view.setTextColor(context.getResources().getColor(R.color.gainsboro));
        view.setBackgroundResource(R.drawable.grayline3_wihte_item);
        handler.sendMessage(MyMessage.getMessage(2, phone));
    }

    private void uncheckButton(TextView view) {
        view.setTextColor(context.getResources().getColor(R.color.login_yellow));
        view.setBackgroundResource(R.drawable.yellowline3_wihte_item);
        view.setText(" 点击获取验证码 ");
        flag = true;
    }

}
